import 'dart:async';

import 'package:amway_superapp_creator_plugin/config/colors_config.dart';
import 'package:amway_superapp_creator_plugin/utils/toast_util.dart';
import 'package:amway_superapp_creator_plugin/viewmodels/edit_phone_model.dart';
import 'package:amway_superapp_creator_plugin/views/base_view.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';

typedef StringCallBack = Function(String mobile);

class EditPhoneDialog extends StatefulWidget {
  final bool outsideDismiss; //点击弹窗外部，关闭弹窗，默认为true true：可以关闭 false：不可以关闭
  final StringCallBack confirmCallback; //点击确定按钮回调
  final Function dismissCallback;
  String mobile;

  EditPhoneDialog(
      {Key key,
      this.outsideDismiss = true,
      this.confirmCallback,
      this.mobile,
      this.dismissCallback})
      : super(key: key); //弹窗关闭回调

  @override
  _EditPhoneDialogState createState() => _EditPhoneDialogState();
}

class _EditPhoneDialogState extends State<EditPhoneDialog> {
  bool isValuable = false;

  _confirmDialog(String mobile) {
    _dismissDialog();
    if (widget.confirmCallback != null) {
      widget.confirmCallback(mobile);
    }
  }

  _dismissDialog() {
    if (widget.dismissCallback != null) {
      widget.dismissCallback();
    }
    Navigator.of(context).pop();
  }

  @override
  void initState() {
    super.initState();
    if (widget.mobile.isNotEmpty) {
      isValuable = true;
    } else {
      isValuable = false;
    }
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    return BaseView<EditPhoneModel>(
      onModelReady: (model) async {},
      model: EditPhoneModel(api: Provider.of(context)),
      builder: (context, model, child) {
        if (widget.mobile.isNotEmpty) {
          model.value = widget.mobile;
          widget.mobile = "";
        }
        return WillPopScope(
            child: GestureDetector(
              onTap: () {},
              child: Material(
                type: MaterialType.transparency,
                child: Center(
                  child: Container(
                    padding: EdgeInsets.only(left: 20, right: 20, bottom: 20),
                    width: size.width * 0.8,
                    child: Stack(
                      children: [
                        Positioned(
                          child: InkWell(
                              onTap: () {
                                _dismissDialog();
                              },
                              child: Icon(Icons.clear)),
                          right: 0,
                          top: 10,
                        ),
                        Column(
                          mainAxisSize: MainAxisSize.min, //自适应高度
                          children: [
                            Container(
                              padding:
                                  EdgeInsets.only(left: 24, right: 24, top: 15),
                              child: Center(
                                child: Text(
                                  "修改手机号",
                                  textAlign: TextAlign.center,
                                  style: TextStyle(
                                      color: ColorsConfig.c_2c2c2c,
                                      fontSize: ScreenUtil().setSp(22)),
                                ),
                              ),
                            ),
                            Row(
                              crossAxisAlignment: CrossAxisAlignment.end,
                              children: [
                                Expanded(
                                    child: TextField(
                                  keyboardAppearance: Brightness.light,
                                  controller: TextEditingController.fromValue(
                                      TextEditingValue(
                                          text: model.value,
                                          selection: new TextSelection
                                                  .fromPosition(
                                              TextPosition(
                                                  affinity:
                                                      TextAffinity.downstream,
                                                  offset: model.value.isEmpty
                                                      ? 0
                                                      : model.value.length)))),
                                  style: TextStyle(
                                      color: model.isPhoneError == true
                                          ? ColorsConfig.c_c53434
                                          : ColorsConfig.c_000000,
                                      fontSize: ScreenUtil().setSp(16)),
                                  autofocus: true,
                                  keyboardType: TextInputType.number,
                                  inputFormatters: _getTextInputFormatter(11),
                                  decoration: InputDecoration(
                                      contentPadding:
                                          const EdgeInsets.symmetric(
                                              vertical: 0.0),
                                      border: InputBorder.none,
                                      hintText: "输入手机号",
                                      hintStyle: TextStyle(
                                          color: ColorsConfig.c_4D000000,
                                          fontSize: ScreenUtil().setSp(16)),
                                      labelText: "手机号",
                                      labelStyle: TextStyle(
                                          color: ColorsConfig.c_4D000000,
                                          fontSize: ScreenUtil().setSp(12))),
                                  onChanged: (value) {
                                    model.change(value);
                                    if (model.isPhoneError) {
                                      model.phoneError(false);
                                    }
                                  },
                                )),
                                model.value.isNotEmpty
                                    ? Container(
                                        margin: EdgeInsets.fromLTRB(
                                            ScreenUtil().setWidth(10),
                                            0,
                                            ScreenUtil().setWidth(10),
                                            ScreenUtil().setWidth(10)),
                                        child: InkWell(
                                            onTap: () {
                                              if (_countdownTimer != null) {
                                                _countdownTimer.cancel();
                                                _countdownTimer = null;
                                                _countdownNum = 59;
                                              }
                                              model.phoneError(false);
                                              model.send(false);
                                              model.change("");
                                              _codeCountdownStr = '获取验证码';
                                            },
                                            child: Icon(
                                              Icons.cancel,
                                              size: ScreenUtil().setSp(18),
                                            )))
                                    : Container(),
                                Container(
                                  margin: EdgeInsets.fromLTRB(
                                      0, 0, 0, ScreenUtil().setWidth(8)),
                                  child: InkWell(
                                    onTap: () {
                                      if (model.isSend) {
                                        return;
                                      }
                                      if (model.value.isNotEmpty) {
                                        var hasMatch = RegExp(
                                                r'^((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\d{8}$')
                                            .hasMatch(model.value);

                                        if (hasMatch) {
                                          model.sendMsg(back: (result, msg) {
                                            if (result) {
                                              model.send(true);
                                              ToastUtils.showShortToast("发送成功");
                                              reGetCountdown(model);
                                            } else {
                                              model.send(false);
                                              ToastUtils.showShortToast(msg);
                                            }
                                          });
                                        } else {
                                          model.phoneError(true);
                                          ToastUtils.showShortToast(
                                              "手机号错误，请重新填写");
                                        }
                                      }
                                    },
                                    child: Text(
                                      model.value.isEmpty
                                          ? "获取验证码"
                                          : _codeCountdownStr,
                                      style: TextStyle(
                                          color: model.value.isNotEmpty &&
                                                  model.value.length == 11
                                              ? ColorsConfig.c_0094a8
                                              : ColorsConfig.c_4D000000,
                                          fontSize: ScreenUtil().setSp(16)),
                                    ),
                                  ),
                                )
                              ],
                            ),
                            Divider(
                                height: ScreenUtil().setHeight(1),
                                color: ColorsConfig.c_80000000),
                            TextField(
                                onChanged: (value) {
                                  model.setCode(value);
                                },
                                keyboardAppearance: Brightness.light,
                                controller: TextEditingController.fromValue(TextEditingValue(
                                    text: model.code,
                                    selection: new TextSelection.fromPosition(TextPosition(
                                        affinity: TextAffinity.downstream,
                                        offset: model.code.isEmpty
                                            ? 0
                                            : model.code.length)))),
                                autofocus: true,
                                enabled: model.isSend == true ? true : false,
                                style: TextStyle(
                                    color: ColorsConfig.c_000000,
                                    fontSize: ScreenUtil().setSp(16)),
                                decoration: InputDecoration(
                                    contentPadding: const EdgeInsets.symmetric(
                                        vertical: 0.0),
                                    border: InputBorder.none,
                                    hintText: "输入验证码",
                                    hintStyle: TextStyle(
                                        color: ColorsConfig.c_4D000000,
                                        fontSize: ScreenUtil().setSp(16)),
                                    labelText:
                                        model.isSend == true ? "验证码" : "输入验证码",
                                    labelStyle: TextStyle(
                                        color: ColorsConfig.c_4D000000,
                                        fontSize: model.isSend == true
                                            ? ScreenUtil().setSp(12)
                                            : ScreenUtil().setSp(16))),
                                keyboardType: TextInputType.number,
                                inputFormatters: _getTextInputFormatter(6)),
                            Divider(
                                height: ScreenUtil().setHeight(1),
                                color: ColorsConfig.c_80000000),
                            Container(
                              width: ScreenUtil().setHeight(146),
                              height: ScreenUtil().setHeight(50),
                              margin: EdgeInsets.only(
                                  top: ScreenUtil().setHeight(20)),
                              child: RaisedButton(
                                shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(25)),
                                color: model.value.isNotEmpty &&
                                        model.code.isNotEmpty
                                    ? ColorsConfig.c_396E75
                                    : ColorsConfig.c_b3396E75,
                                onPressed: () {
                                  if (model.value.isEmpty) {
                                    if (isValuable) {
                                      ToastUtils.showShortToast("已清空手机号");
                                    }
                                    _confirmDialog(model.value);
                                    return;
                                  }
                                  if (model.code.isEmpty) {
                                    ToastUtils.showShortToast("请填写验证码");
                                    return;
                                  }
                                  model.verify(back: (result, msg) {
                                    if (result) {
                                      _confirmDialog(model.value);
                                    } else {
                                      model.send(true);
                                      ToastUtils.showShortToast("验证码错误，请重新填写");
                                    }
                                  });
                                },
                                child: Text(
                                  "确认",
                                  style: TextStyle(
                                      color: Colors.white,
                                      fontSize: ScreenUtil().setSp(18)),
                                ),
                              ),
                            )
                          ],
                        )
                      ],
                    ),
                    decoration: BoxDecoration(
                        color: Color(0xFFFFFFFF),
                        borderRadius: BorderRadius.circular(10.0)),
                  ),
                ),
              ),
            ),
            onWillPop: () async {
              return widget.outsideDismiss ? _dismissDialog() : null;
            });
      },
    );
  }

  ///输入范围
  List<TextInputFormatter> _getTextInputFormatter(int length) {
    return <TextInputFormatter>[
      FilteringTextInputFormatter.digitsOnly,
      LengthLimitingTextInputFormatter(length)
    ];
  }

  Timer _countdownTimer;
  String _codeCountdownStr = "获取验证码";
  int _countdownNum = 59;

  void reGetCountdown(EditPhoneModel model) {
    setState(() {
      if (_countdownTimer != null) {
        return;
      }
      // Timer的第一秒倒计时是有一点延迟的，为了立刻显示效果可以添加下一行。
      _codeCountdownStr = '已发送验证码(${_countdownNum--})';
      _countdownTimer = new Timer.periodic(new Duration(seconds: 1), (timer) {
        setState(() {
          if (_countdownNum > 0) {
            _codeCountdownStr = '已发送验证码(${_countdownNum--})';
          } else {
            _codeCountdownStr = '获取验证码';
            _countdownNum = 59;
            _countdownTimer.cancel();
            _countdownTimer = null;
          }
        });
      });
    });
  }

  // 不要忘记在这里释放掉Timer
  @override
  void dispose() {
    _countdownTimer?.cancel();
    _countdownTimer = null;
    super.dispose();
  }
}
